//先分离线程，再取消线程，观察现象


#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <functional>
using namespace std;

void* threadRoutine(void* args)
{
    int cnt = 5;
    while(cnt--)
    {
        cout << "thread is running..." << endl;
        sleep(1);
    }
    return nullptr;
}

int main()
{
    pthread_t tid;
    pthread_create(&tid, nullptr, threadRoutine, nullptr);
    sleep(1);

    pthread_detach(tid); 

    int n = pthread_cancel(tid); //取消tid线程
    cout << "main thread cancel done, " << " n: " << n << endl;

    void* ret = nullptr;
    n = pthread_join(tid, &ret); 
    cout << "main thread join done, " << " n: " << n  << ", thread return:  "<< (int64_t)ret << endl;
    return 0;
}

//结论: 线程被分离后，可以被取消，不能被join

//如果线程被取消，则退出结果ret就是PTHREAD_CANCELED
// #define PTHREAD_CANCELED ((void *) -1)